package net.alpcontrol.bi.bootstrap.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * @author rickyjins
 */
public class JacksonUtil {
    private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
    private static ObjectMapper objectMapper(String datePattern) {
        ObjectMapper objectMapper;
        (objectMapper = new ObjectMapper()).configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
        objectMapper.setDateFormat(simpleDateFormat);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return objectMapper;
    }

    public static String toJsonString(Object entity) {
        if (BeanUtils.isEmpty(entity)) {
            return null;
        } else {
            try {
                return objectMapper("yyyy-MM-dd HH:mm:ss").writeValueAsString(entity);
            } catch (JsonProcessingException var1) {
                logger.warn(var1.getMessage(), var1);
                return null;
            }
        }
    }

    public static <T>T toBean(String jsonString, Class<T> clazz) {
        if(StringUtils.isBlank(jsonString)){
            return null;
        }
        T t = null;
        try {
            t = objectMapper("yyyy-MM-dd HH:mm:ss").readValue(jsonString, clazz);
        } catch (JsonProcessingException e) {
            logger.error("字符串转换对象出错: " + jsonString, e);
        }
        return t;
    }

    public static <T>T toBean(String jsonString, TypeReference<T> typeReference) {
        if(StringUtils.isBlank(jsonString)){
            return null;
        }
        T t = null;
        try {
            t = objectMapper("yyyy-MM-dd HH:mm:ss").readValue(jsonString, typeReference);
        } catch (JsonProcessingException e) {
            logger.error("字符串转换对象出错: " + jsonString, e);
        }
        return t;
    }

    public static <T> T toBean(String jsonString, T t) {
        if(StringUtils.isBlank(jsonString)){
            return null;
        }
        try {
            objectMapper("yyyy-MM-dd HH:mm:ss").readerForUpdating(t).readValue(jsonString);
        } catch (Exception e) {
            logger.error("字符串转换对象出错: " + jsonString, e);
        }
        return t;
    }
}
